<script setup lang="ts">
import Page from '@/components/Page.vue';
import { http } from '@/services/http';
import { useUserStore } from '@/stores/user';
import type { Comment, OrderPageData, ResponseData, Transaction, TransactionForm } from '@/types';
import { getBookImageUrl } from '@/utils';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import CommentDialog from './CommentDialog.vue';
import OrderDialog from './OrderDialog.vue';

const pageData = reactive({
  buyer_id: 0,
  seller_id: 0,
  //分页相关模型数据
  nationality: '',
  currentPage: 1, // 当前页码
  pageSize: 15, // 每页显示的记录数
  total: 60, // 总记录数
  queryString: '', // 查询条件
});
const dialogCommentForm = ref(false);
const defaultCommentForm = {
  reviewer: 0,
  imgList: '',
  hasRecommented: false,
  id: 0,
  order_id: 0,
  book_name: '',
  transaction_date: '',
  rate: 0,
  content: '',
  fileList: [],
  book_img: '',
};

const commentForm = reactive<Comment>(defaultCommentForm);
const transactionForm = ref<TransactionForm>({
  buyer_id: 0,
  buyer_name: '',
  buyer_college: '',
  buyer_major: '',
  seller_id: 0,
  seller_name: '',
  seller_college: '',
  seller_major: '',
  transaction_date: '',
  amount: 0,
  books_id: 0,
  quantity: 0,
  books_name: '',
  book_code: '',
});
const transitionList = ref<Transaction[]>([]);
const dialogFormVisible4 = ref(false);
const route = useRoute();
const router = useRouter();
const getTransactionListByPage = () => {
  http.post<ResponseData<OrderPageData>>('/transaction/page', pageData).then((res) => {
    console.log(909, res);

    transitionList.value = res.data.list;
    pageData.total = res.data.total;
  });
};
const handleCurrentChange = (u: number) => {
  pageData.currentPage = u;
  getTransactionListByPage();
};
interface CommentData {
  order_id: number;
  comment_id: number;
}
const getCommentId = (data: CommentData) => {
  const params3 = {
    order_id: data.order_id,
    comment_id: data.comment_id,
  };

  http.post('/transaction/handleComId', params3);
};
const handleDetails = (id: number) => {
  dialogFormVisible4.value = true;
  http
    .get<ResponseData>('/transaction/one', { id: id })
    .then((res) => {
      transactionForm.value = res.data;
    })
    .catch((error) => {
      ElMessage.error('请求失败，请稍后再试');
    });
};
const handleDelete = (id: number) => {
  ElMessageBox.confirm('此操作将永久删除该订单, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      http.get<ResponseData>('/transaction/del', { id: id }).then((ResponseData) => {
        ElMessage({ type: 'success', message: ResponseData.msg });
        getTransactionListByPage();
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      });
    });
};

const handleCommentSubmitted = (order_id: number) => {
  if (order_id) {
    const num1 = order_id;
    console.log(num1);

    http
      .get('/transaction/hascommented', { num1: num1 })
      .then((response) => {
        console.log('Response:', response);
        const index = transitionList.value.findIndex((item) => item.id === order_id);
        if (index !== -1) {
          transitionList.value[index].hasCommented = true;
        }
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  }
};

const handleCommentClick = (row: any, hasCommented: boolean) => {
  if (hasCommented) {
    router.push({ name: 'comment', params: { commentId: row.comment_id } });
  } else {
    dialogCommentForm.value = true;
    http
      .get<ResponseData>('/transaction/one', { id: row.id })
      .then((res) => {
        commentForm.book_name = res.data.books_name;
        commentForm.transaction_date = res.data.transaction_date;
      })
      .catch((error) => {
        ElMessage.error('请求失败，请稍后再试');
      });
    http.get<ResponseData>('/transaction/two', { id: row.id }).then((res) => {
      commentForm.book_img = res.data.book_img;
      commentForm.order_id = row.id;
    });
  }
};

const userStore = useUserStore();

const handleBuy = () => {
  pageData.buyer_id = userStore.userInfo.id;
  console.log(pageData.buyer_id);
  http.post<ResponseData<OrderPageData>>('/transaction/findBuy', pageData).then((res) => {
    transitionList.value = res.data.list;
    pageData.total = res.data.total;
  });
};

const handleReview = () => {
  pageData.buyer_id = userStore.userInfo.id;
  console.log(pageData.buyer_id);
  http.post<ResponseData<OrderPageData>>('/transaction/findNoReview', pageData).then((res) => {
    transitionList.value = res.data.list;
    pageData.total = res.data.total;
  });
};

const handleSell = () => {
  pageData.seller_id = userStore.userInfo.id;
  http.post<ResponseData<OrderPageData>>('/transaction/findSell', pageData).then((res) => {
    transitionList.value = res.data.list;
    pageData.total = res.data.total;
  });
};

onMounted(() => {
  const transactionId = route.params.transactionId;
  if (transactionId) {
    handleDetails(Number(transactionId));
  }
  const ownerId = Number(route.params.ownerId);
  console.log(111, ownerId);
  const type = route.params.type;
  console.log(12121, type);
  if (type == 'sell') {
    console.log(11111111111);

    handleSell();
  } else if (type == 'buy') {
    handleBuy();
  } else if (type == 'review') {
    handleReview();
  } else {
    handleBuy();
  }
});
</script>

<template>
  <Page class="book-view">
    <template #header>
      <div class="content-header">
        <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>订单记录</el-breadcrumb-item>
          <el-breadcrumb-item>所有订单记录</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </template>
    <div class="filter-container">
      <el-input placeholder="交易ID/买家ID/买家ID" v-model="pageData.queryString" class="filter-item" />
      <el-button @click="handleCurrentChange(1)">查询</el-button>
      <el-button type="success" @click="handleBuy">我买到的</el-button>
      <el-button type="primary" @click="handleSell">我卖出的</el-button>
    </div>
    <el-table
      class="tableContainer"
      size="small"
      current-row-key="id"
      :data="transitionList"
      stripe
      highlight-current-row
    >
      <el-table-column type="index" label="序号" width="50" />
      <el-table-column prop="id" label="交易ID" align="center"></el-table-column>
      <el-table-column prop="book_image" label="书本图片">
        <template v-slot="scope">
          <el-image :src="getBookImageUrl(scope.row.book_img)" style="width: 60px; height: auto">
            <template #error>
              <div class="img-fallback">
                <el-icon><Notebook /></el-icon>
                <div class="img-fallback-text">Cover</div>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="book_name" label="书本名称" align="center"></el-table-column>
      <el-table-column prop="buyer_name" label="买家昵称" align="center"></el-table-column>
      <el-table-column prop="seller_name" label="商家昵称" align="center"></el-table-column>
      <el-table-column prop="transaction_date" label="交易日期" align="center"> </el-table-column>
      <el-table-column prop="amount" label="成交金额" align="center"></el-table-column>
      <el-table-column prop="quantity" label="交易数量" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="300">
        <template #default="scope">
          <el-button
            :type="scope.row.hasCommented ? 'info' : 'success'"
            size="small"
            @click="handleCommentClick(scope.row, scope.row.hasCommented)"
            class="comment-button"
            :class="{ 'has-commented': scope.row.hasCommented }"
          >
            <span class="button-text">{{ scope.row.hasCommented ? '已评论' : '去评价' }}</span>
          </el-button>
          <el-button type="primary" size="small" @click="handleDetails(scope.row.id)">查看具体信息</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      size="small"
      class="pagination"
      @current-change="handleCurrentChange"
      :current-page="pageData.currentPage"
      :page-size="pageData.pageSize"
      layout="total, prev, pager, next, jumper"
      :total="pageData.total"
    >
    </el-pagination>
  </Page>
  <order-dialog v-model="transactionForm" v-model:visible4="dialogFormVisible4" />
  <comment-dialog
    v-model="commentForm"
    v-model:commentDialog="dialogCommentForm"
    @comment-submitted="handleCommentSubmitted"
    @comment-id="getCommentId"
  />
</template>

<style>
.comment-button {
  position: relative;
}

.comment-button .button-text {
  transition: opacity 0.3s;
}

.comment-button.has-commented .button-text {
  opacity: 1;
}

.comment-button.has-commented:hover .button-text {
  opacity: 0;
}

.comment-button.has-commented:hover::after {
  color: aqua;
  content: '查看评论';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  white-space: nowrap;
}
/* 闪烁动画 */
@keyframes blink {
  0% {
    background-color: yellow;
  }
  50% {
    background-color: transparent;
  }
  100% {
    background-color: yellow;
  }
}

.blink {
  animation: blink 1s infinite;
}
.filter-container {
  display: flex;
  margin: 16px 0;
}
.filter-item {
  width: 200px;
  margin-right: 12px;
}
.pagination {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
